package com.jcfk.eam.service.base;

import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.business.enums.AvailableStatus;
import com.jcfk.common.business.enums.DeleteFlag;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.core.utils.BeanUtils;
import com.jcfk.common.core.utils.IdUtils;
import com.jcfk.common.security.utils.SecurityUtils;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.eam.dao.base.EamAssetPositionDao;
import com.jcfk.eam.domain.dto.base.EamAssetPositionDTO;
import com.jcfk.eam.domain.po.base.EamAssetPosition;
import com.jcfk.eam.domain.po.main.EamAssetInfo;
import com.jcfk.eam.domain.query.base.EamAssetPositionQuery;
import com.jcfk.eam.service.main.EamAssetInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 资产组成部位
 *
 * @author yrl
 * @date 2024-12-04
 */
@Service
public class EamAssetPositionService extends BaseService<EamAssetPositionDao, EamAssetPosition> {

    @Autowired
    private EamAssetInfoService eamAssetInfoService;

    /**
     * EamAssetPosition分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamAssetPositionDTO> queryByPage(DataPage<EamAssetPositionDTO> page, EamAssetPositionQuery query) {
        // 分页查询
        query.setPositionCode(StringUtils.isEmpty(query.getPositionCode()) ? query.getPositionCode() : query.getPositionCode() + "%");
        query.setPositionName(StringUtils.isEmpty(query.getPositionName()) ? query.getPositionName() : query.getPositionName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamAssetPosition是已经存在
     *
     * @param dto 插入对象
     */
    public RetResult<String> isValid(EamAssetPositionDTO dto) {
        QueryWrapper<EamAssetPosition> qw = new QueryWrapper<>();
        qw.eq("deleted", 0);
        // 判断编号
        if (StrUtil.isNotEmpty(dto.getPositionCode())) {
            // 修改时添加条件
            if (!StrUtil.isEmpty(dto.getId())) {
                qw.lambda().ne(EamAssetPosition::getId, dto.getId());
            }
            qw.lambda().eq(EamAssetPosition::getAssetKind, dto.getAssetKind());
            qw.lambda().eq(EamAssetPosition::getPositionCode, dto.getPositionCode());
            qw.lambda().eq(EamAssetPosition::getDeleted, DeleteFlag.NOTDELETED.getValue());

            Integer count = this.baseMapper.selectCount(qw);
            if (count > 0) {
                return RetResult.fail("编号已存在");
            }
        }
        return RetResult.ok();
    }

    /**
     * 插入资产组成部位
     *
     * @param dto 插入对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamAssetPositionDTO dto) {

        // 保存
        EamAssetPosition item = new EamAssetPosition();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);
        item.setId(IdUtils.simpleUUID());
        this.setAllInfo(item);
        item.setEnabled(AvailableStatus.ENABLE.getValue());

        super.save(item);
    }

    /**
     * 更新资产组成部位
     *
     * @param dto 更新对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamAssetPositionDTO dto) {

        // 保存
        EamAssetPosition item = new EamAssetPosition();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);
        this.setAllInfo(item);

        super.updateById(item);
    }

    /**
     * 根据批量主键删除资产组成部位(逻辑删除)
     *
     * @param dto 删除dto中包含的ids属性值
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(EamAssetPositionDTO dto) {

        EamAssetPosition item = new EamAssetPosition();

        this.setDefaultValue(item);
        item.setVersion(dto.getVersion());
        item.setDeleted(1);

        QueryWrapper<EamAssetPosition> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamAssetPosition item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setDeleted(0);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }

        if (item.getSort() == null) {
            item.setSort("1");
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取资产组成部位信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamAssetPositionDTO get(String id) {
        // 查询数据
        EamAssetPositionDTO dto = this.baseMapper.queryById(id);
        if(StrUtil.isEmpty(dto.getAssetId())){
            return dto;
        }
        EamAssetInfo info = eamAssetInfoService.getById(dto.getAssetId());
        dto.setAssetCode(info.getAssetCode());
        dto.setAssetName(info.getAssetName());
        return dto;
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamAssetPositionDTO>
     */
    public List<EamAssetPositionDTO> getList(EamAssetPositionQuery query) {
        // 查询条件
        QueryWrapper<EamAssetPosition> ew = new QueryWrapper<>();
        ew.eq(!StrUtil.isEmpty(query.getAssetTypeId()), "eamAssetPosition.asset_type_id", query.getAssetTypeId());
        ew.likeRight(!StrUtil.isEmpty(query.getPositionCode()), "eamAssetPosition.position_code", query.getPositionCode());
        ew.likeRight(!StrUtil.isEmpty(query.getPositionName()), "eamAssetPosition.position_name", query.getPositionName());
        ew.eq("eamAssetPosition.deleted", DeleteFlag.NOTDELETED.getValue());
        // 查询数据
        EamAssetInfo info;
        List<EamAssetPositionDTO> list = this.baseMapper.queryList(ew);
        for(EamAssetPositionDTO item : list){
            if(StrUtil.isEmpty(item.getAssetId())){
                continue;
            }
            info = eamAssetInfoService.getById(item.getAssetId());
            item.setAssetCode(info.getAssetCode());
            item.setAssetName(info.getAssetName());
        }

        return list;
    }

    /**
     * 根据主键获取资产组成部位信息
     *
     * @param id 主键
     */
    public void deleteItem(String id) {
        EamAssetPosition item = getById(id);
        this.setDefaultValue(item);
        item.setDeleted(1);

        this.updateById(item);
    }


    public void setAllInfo(EamAssetPosition item) {
        QueryWrapper<EamAssetPosition> qw = new QueryWrapper<>();
        qw.lambda().eq(EamAssetPosition::getId, item.getParentId());

        EamAssetPosition parent = this.baseMapper.selectOne(qw);
        if (parent == null) {
            item.setAllId(item.getId());
            item.setAllCode(item.getPositionCode());
            item.setAllName(item.getPositionName());
        } else {
            item.setAllId(parent.getAllId() + "," + item.getId());
            item.setAllCode(parent.getAllCode() + "," + item.getPositionCode());
            item.setAllName(parent.getAllName() + "," + item.getPositionName());
        }
    }


    /**
     * 根据条件获取位置信息树
     *
     * @param query 查询条件
     */
    public List<EamAssetPositionDTO> getTree(EamAssetPositionQuery query) {
        List<EamAssetPositionDTO> tree = new ArrayList<>();
        // 获取所有类型
        List<EamAssetPositionDTO> allList = this.getList(query);

        // 排序
        allList.sort(Comparator.comparing(EamAssetPositionDTO::getSort));

        Map<String, List<EamAssetPositionDTO>> parentChildMap = new HashMap<>();
        // 将节点按照父节点进行分组
        for (EamAssetPositionDTO node : allList) {
            String parentTypeId = node.getParentId();
            parentChildMap.computeIfAbsent(parentTypeId, k -> new ArrayList<>()).add(node);
        }

        // 递归组装树结构
        buildTree(tree, parentChildMap, "0");

        return tree;
    }


    private static void buildTree(List<EamAssetPositionDTO> tree, Map<String, List<EamAssetPositionDTO>> parentChildMap, String parentId) {
        List<EamAssetPositionDTO> children = parentChildMap.get(parentId);
        if (children != null) {
            for (EamAssetPositionDTO child : children) {
                List<EamAssetPositionDTO> grandchildren = parentChildMap.get(child.getId());
                if (grandchildren != null) {
                    buildTree(child.getNodes(), parentChildMap, child.getId());
                }
                tree.add(child);
            }
        }
    }

}

